package fr.mma.achievement.servlet;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.googlecode.objectify.Key;

import fr.mma.achievement.controller.AchievementUtils;
import fr.mma.achievement.dao.AchievementDao;
import fr.mma.achievement.model.AchievementType;
import fr.mma.achievement.model.persistence.Achievement;
import fr.mma.livraison.dao.DevDao;
import fr.mma.livraison.model.persistence.Developpeur;

public class AddAchievementServlet extends HttpServlet {

	/** */
	private static final long serialVersionUID = -1130587590562430282L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		super.doGet(req, resp);
		DevDao devDao = new DevDao();
		AchievementDao achievementDao = new AchievementDao();
		List<Developpeur> developpeurs = devDao.getAll();
		List<Achievement> achievements = achievementDao.getAll();
		Map<String, List<Achievement>> achievementGroupByDev = AchievementUtils.groupByDev(achievements);
		for (Developpeur developpeur : developpeurs) {
			List<Achievement> myAchievement = achievementGroupByDev.get(developpeur.getTrigram());
			for (int i = 0; i < AchievementType.values().length; i++) {
				AchievementType currentType = AchievementType.values()[i];
				boolean exist = false;
				if (myAchievement != null) {
					for (Achievement achievement : myAchievement) {
						if (achievement.getType() == currentType) {
							exist = true;
						}
					}
				}
				if (!exist) {
					Achievement achievement = new Achievement(developpeur.getTrigram() + "_" + currentType.name());
					achievement.setType(currentType);
					achievement.setDeveloppeur(new Key<Developpeur>(Developpeur.class, developpeur.getTrigram()));
					achievementDao.save(achievement);
				}
			}
		}
	}

}
